#include "TcpSever.hpp"
#include <memory>
#include "Protocol.hpp"
#include <signal.h>
#include <iostream>
void test(int accepted_sock)
{
    cout << "我是一个测试程序,我的sock是" << accepted_sock << endl;
}
Respon compute_helper(const Requst &req)
{
    Respon res;
    switch (req._op)
    {
    case '+':
        res._result = req._x + req._y;
        break;
    case '-':
        res._result = req._x - req._y;
        break;
    case '*':
        res._result = req._x * req._y;
        break;
    case '/':
        res._result = req._x / req._y;
        break;
    case '%':
        res._result = req._x % req._y;
        break;
    default:
        res._code = 1;
        break;
    }
    return res;
}
void Computer(int accepted_sock)
{
    string inbuffer;
    while (true)
    {
        
        //接收并解码消息
        //string ret = Recv(accepted_sock);
        string ret;
        while(1)
        {
            cout<<"准备接收信息并解码"<<endl;
            cout<<buffer<<endl;
            ret = Decode(accepted_sock,&inbuffer);
            if(ret == "") continue;
            cout<<"解码完毕"<<endl;
            cout<<ret<<endl;
            break;
        }
        
        Requst req;

        //反序列化之前 还需要进行Decode lenth/r/n123 + 456/r/n

        //反序列化消息
        cout<<"反序列化中···";
        req.DeSerialize(ret);
        cout<<"反序列化完成"<<endl;
        //业务逻辑
        Respon res = compute_helper(req);
        //向外发送前 需要进行Encode

        //向外发送
        cout<<"序列化完成，准备编码发送···"<<endl;
        string buffer = res.Serialize();
        buffer = Encode(&buffer);
        if (Send(accepted_sock, buffer) == true)
            logMessage(NORMAL, "发送成功\n");
        
        else
        {
            logMessage(NORMAL, "客户端关闭，停止发送\n");
            break;
        }
    }
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        logMessage(FATAL, "请输入两个参数，待运行程序，端口号\n");
        exit(1);
    }
    signal(SIGPIPE, SIG_IGN);
    uint16_t port = atoi(argv[1]);
    unique_ptr<TcpSever> ts(new TcpSever(port));
    ts->BindService(Computer);
    ts->start();
    return 0;
}